<?php
namespace app\common\mq;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Tdmq\V20200217\Models\SendMessagesRequest;
use TencentCloud\Tdmq\V20200217\TdmqClient;

class PulsarMQ
{
    private $client;

    public function __construct()
    {
        $secretId = env('pulsar.secret_id', '');
        $secretKey = env('pulsar.secret_key', '');
        $queue_endpoint = env('pulsar.queue_endpoint', '');
        $region = env('pulsar.region', '');
        $credential = new Credential($secretId, $secretKey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint($queue_endpoint);
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $this->client = new TdmqClient($credential, $region, $clientProfile);
    }

    /**
     * pulsar 发送单条消息
     * @author 贺强
     * @time   2022/6/19 14:39
     * @param array $param 发送消息参数
     */
    public function sendMessage($param)
    {
        if (empty($param['topic']) || empty($param['payload'])) {
            return false;
        }
        try {
            $req = new SendMessagesRequest();
            $params = [];
            foreach ($param as $k => $v) {
                $params[hump($k)] = $v;
            }
            $req->fromJsonString(json_encode($params));
            return $this->client->SendMessages($req);
        } catch (TencentCloudSDKException $e) {
            return $e->getMessage();
        }
    }
}
